package com.zrkj.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrkj.entity.*;
import com.zrkj.entity.dto.UserDto;
import com.zrkj.entity.vo.LoginVo;
import com.zrkj.entity.vo.Result;
import com.zrkj.exception.SystemErrorType;
import com.zrkj.mapper.TSysUserRoleMapper;
import com.zrkj.mapper.TUserMapper;
import com.zrkj.service.*;
import com.zrkj.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @author : 国良
 * @className : ITUserServiceImpl
 * @package: com.wg.service.impl
 * @description :  服务接口实现
 * @date :  2021-03-04
 */
@Service("iTUserService")
@Slf4j
public class ITUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {
    private static String EMPTY = "";


    @Autowired
    private ITSysResourceService itSysResourceService;
    @Autowired
    private ITSysRoleResourceService itSysRoleResourceService;

    @Autowired
    private ITSysUserRoleService itSysUserRoleService;

    @Autowired
    private TSysUserRoleMapper userRoleMapper;


    /**
     * 添加
     *
     * @param tUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> add(TUser tUser) {
        String uuid = IdWorker.get32UUID();
//        TSysUserRole userRole = new TSysUserRole();
//        userRole.setUserId(uuid);
//        userRole.setRoleId(tUser.getRoleId());
//        itSysUserRoleService.add(userRole);
        tUser.setId(uuid);
        return Result.success(this.save(tUser));
    }

    /**
     * 更新
     *
     * @param tUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> update(TUser tUser) {
        TSysUserRole userRole = new TSysUserRole();
        userRole.setUserId(tUser.getId());
        TSysUserRole role = itSysUserRoleService.queryList(userRole).getData().get(0);
        role.setRoleId(tUser.getRoleId());
        itSysUserRoleService.update(role);
        return Result.success(this.saveOrUpdate(tUser));
    }

    /**
     * 删除
     *
     * @param idList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> delete(List<String> idList) {
        return Result.success(this.removeByIds(idList));
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Override
    public Result<TUser> getById(String id) {
        return Result.success(baseMapper.selectById(id));
    }

    /**
     * 查询列表
     *
     * @param tUser
     * @return
     */
    @Override
    public Result<List<TUser>> queryList(TUser tUser) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>();
        return Result.success(this.list(queryWrapper));
    }

    /**
     * 查询分页列表
     *
     * @param page
     * @param tUser
     * @return
     */
    @Override
    public Result<IPage<TUser>> queryPageList(Page page, UserDto tUser) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>();
        queryWrapper.like(StrUtil.isNotBlank(tUser.getUserName()), "user_name", tUser.getUserName());
        IPage<TUser> pageQuery = this.page(page, queryWrapper);
        for (TUser user : pageQuery.getRecords()) {
            QueryWrapper<TSysUserRole> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(true, "user_id", user.getId());
            List<TSysUserRole> tSysUserRoles = userRoleMapper.selectList(queryWrapper1);
            if (!IterUtil.isEmpty(tSysUserRoles)) {
                String id = tSysUserRoles.get(0).getRoleId();
                user.setRoleId(id);
            }
        }
        return Result.success(pageQuery);
    }


    @Override
    public TUser getByName(String username) {

        QueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>();
        queryWrapper.eq("user_name", username);
        TUser user = this.getOne(queryWrapper);
        return user;
    }

    @Override
    public Result login(String iotLogin, String username, String password) {

        return checkUser(username, password, EMPTY);


    }

    @Autowired
    private ITSysRoleService itSysRoleService;

    private Result checkUser(String username, String password, String iotToken) {
        TUser user = this.getByName(username);
        if (ObjectUtils.isEmpty(user)) {
            return Result.success(SystemErrorType.USER_NOT_EXIST);
        }
        if (password.equals(user.getQaz())) {
            String token = JwtUtil.generateToken(user.getId(), username, iotToken);
            LoginVo loginVo = new LoginVo();
            loginVo.setToken(token);
            loginVo.setRole(user.getRole());
            String userId = user.getId();
            loginVo.setUId(userId);
//            TSysUserRole userRole = new TSysUserRole();
//            userRole.setUserId(userId);
//            List<TSysUserRole> data = itSysUserRoleService.queryList(userRole).getData();
//            if (CollectionUtils.isEmpty(data)) {
//                return Result.success(loginVo);
//            }
//            String roleId = data.get(0).getRoleId();
//            Result<TSysRole> byId = itSysRoleService.getById(roleId);
//            if (!ObjectUtils.isEmpty(byId.getData())) {
//                loginVo.setInfo(byId.getData());
//            }
            return Result.success(loginVo);
        } else {
            return Result.success(SystemErrorType.USER_NOT_EXIST);
        }
    }


    public Result getResources(LoginVo loginVo) {
        TSysRoleResource tSysRoleResource = new TSysRoleResource();
        tSysRoleResource.setRoleId(loginVo.getRole());
        Result<List<TSysRoleResource>> result = itSysRoleResourceService.queryList(tSysRoleResource);
        if (CollectionUtils.isEmpty(result.getData())) {
            return Result.success();
        }
        List<TSysResource> tSysResources = new ArrayList<>();
        for (TSysRoleResource datum : result.getData()) {
            TSysResource byId = itSysResourceService.getById(datum.getResourceId());
            if (Objects.nonNull(byId)) {
                tSysResources.add(byId);
            }
        }
        return Result.success(tSysResources);
    }


}
